<template>
  <div>
    <myDivider name="车位管理费"></myDivider>
    <div class="Top">
      <div style="display: flex;">

        <el-input style="width: 160px;" v-model="key1" placeholder="根据小区名称搜索" @keyup.enter.native="getTableList"
                  clearable></el-input>

        <el-input style="width: 150px;margin-left: 15px;" v-model="key2" placeholder="根据车位号搜索"
                  @keyup.enter.native="SouSuo" clearable></el-input>

        <el-date-picker style="width: 250px;margin-left: 20px;" @change="SouSuo" value-format="yyyy-MM-dd"
                        v-model="keyTime" type="daterange" range-separator=" " start-placeholder="创建时间" end-placeholder="请选择时间段">
        </el-date-picker>

        <el-button type="primary" style=" margin-left: 15px" @click="SouSuo">查询</el-button>
        <el-button style="margin-left: 15px" @click="reset">重置</el-button>
      </div>
      <el-button style="margin-top: 10px;" type="primary" @click="addClick">新增</el-button>

    </div>
    <el-table class="tableBox" :data="TableData" style="width: 100%">
      <el-table-column align="center" prop="residentialName" label="小区名称" width="200px">
      </el-table-column>
      <el-table-column align="center" prop="code" label="车位号">
      </el-table-column>
      <el-table-column align="center" prop="amount" label="管理费" width="100px">
      </el-table-column>
      <el-table-column align="center" prop="managementPeriod" label="管理费期限" width="200px">
      </el-table-column>
      <el-table-column align="center" prop="remarks" label="备注" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="operatorName" label="最后修改人员" width="100px">
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200px">
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px">
        <template slot-scope="scope">
          <div class="textBtn">
            <el-row>
              <el-col class="el" :span="6">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="updateClick(scope.row)">编辑</span>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
    </el-table>


    <!-- 新增租赁弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="550px"
               :title="mainPopType == 'add' ? '新增车位管理费' : '修改车位管理费'"
               :visible.sync="mainPopShow">
      <el-divider></el-divider>

      <el-form :model="mainForm" :rules="rules" ref="mainForm" label-width="150px">
        <el-form-item label="选择小区：" prop="residentialName" required>
          <div style="display: flex;">
            <el-button @click="toSelect('小区')"
                       :disabled="mainPopType == 'update'">选择</el-button>
            <el-input style="width: 230px;" v-model="mainForm.residentialName" disabled
                      placeholder="请选择所属小区"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="选择车位：" prop="carSpaceName" required>
          <div style="display: flex;">
            <el-button @click="toSelect('车位')"
                       :disabled="mainPopType == 'update'">选择</el-button>
            <el-input style="width: 230px;" v-model="mainForm.carSpaceName" disabled placeholder="请选择车位"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="归属人：" prop="ownerName" >
          <el-input disabled style="width: 300px;"  v-model="mainForm.ownerName"
                    maxlength="20" placeholder="请输入归属人"></el-input>
        </el-form-item>
        <el-form-item label="租赁人：" prop="tenantUserName" >
            <el-input style="width: 300px;" v-model="mainForm.tenantUserName" disabled placeholder="请选择租赁人"></el-input>
        </el-form-item>
        <el-form-item label="金额：">
          <el-input style="width: 300px;" v-model="mainForm.amount" type="number" maxlength="10"
                     placeholder="请输入金额"></el-input>
        </el-form-item>

        <el-form-item label="管理费开始期限：" prop="managementFeesStart" required>
          <el-date-picker style="width: 300px;" v-model="mainForm.managementFeesStart" type="date"
                           value-format="yyyy-MM-dd" placeholder="请选择开始日期"
                          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="缴纳：" prop="count" required>
          <el-input style="width: 300px;" v-model="mainForm.count" type="number" maxlength="10" @input="updataManagementFeesEnd"
                     placeholder="请输入月数"></el-input>
          个月
        </el-form-item>
        <el-form-item label="管理费结束期限：" prop="managementFeesEnd" required>
          <el-date-picker style="width: 300px;" v-model="mainForm.managementFeesEnd" type="date"
                          value-format="yyyy-MM-dd" placeholder="请选择结束日期" disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注：" prop="remarks" required>
          <el-input style="width: 300px;" rows="4" v-model="mainForm.remarks" type="textarea" maxlength="200"
                    show-word-limit placeholder="请输入" ></el-input>

        </el-form-item>
      </el-form>

      <el-divider></el-divider>
      <div  slot="footer"
            style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="mainPopShow = false">取 消</el-button>
        <el-button type="primary" @click="mainPopOk">确
          定</el-button>
      </div>

    </el-dialog>





    <!-- 选择弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" :title="'选择' + selectType"
               :visible.sync="selectShow">
      <el-divider v-if="selectType != '车位'"></el-divider>
      <!-- 筛选项 -->
      <!-- 筛选项 -->
      <!-- 筛选项 -->
      <div v-if="selectType == '小区'" style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-cascader change-on-select style="width: 200px;" clearable v-model="selectPopKeyArea"
                     @change="cascaderChange" :props="props" placeholder="请选择地区"></el-cascader>
        <el-input size="medium" style="width: 200px;" v-model="selectPopKeyResidentialName"
                  placeholder="输入小区名称搜索"></el-input>
        <el-button size="medium" type="primary" @click="getSelectPopData">查询</el-button>
      </div>

      <div v-if="selectType == '车位'" style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input size="medium" style="width: 200px;" v-model="selectPopKeycarSpaceNumber"
                  placeholder="输入车位号搜索"></el-input>
        <el-button size="medium" type="primary" @click="getSelectPopData">查询</el-button>
      </div>

      <!-- 表格 --> <!-- 表格 --> <!-- 表格 --> <!-- 表格 -->
      <div class="popTableStyle">
        <el-table ref="selectTable" :data="selectData" style="width: 100%" height="300px" highlight-current-row>

          <el-table-column v-if="selectType == '小区'" align="center" prop="areaName" label="地区">
          </el-table-column>
          <el-table-column v-if="selectType == '小区'" align="center" prop="name" label="小区名称">
          </el-table-column>

          <el-table-column v-if="selectType == '车位'" align="center" prop="pictureUrl" label="车位照片">
            <template slot-scope="scope">
              <el-image v-if="scope.row.pictureUrl" style="width: 80px; height: 60px" :src="scope.row.pictureUrl"
                        :preview-src-list="[...scope.row.pictureUrl]">
              </el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column v-if="selectType == '车位'" align="center" prop="code" label="车位号">
          </el-table-column>
        </el-table>
      </div>

      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectShow = false">取 消</el-button>
        <el-button type="primary" @click="selectOk">确
          定</el-button>
      </div>

    </el-dialog>


    <!-- 分页器 -->
    <myPagination :pageNum="pageNum" :total="totalSize" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>





<script>
import axios from 'axios'
export default {
  components: {
  },
  data() {
    return {
      // 顶部筛选 ===================
      key1: '',
      key2: '',
      keyTime: ['', ''],
      //===================  顶部筛选

      // 主要表格==================
      TableData: [{ name: '1', img: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' }], //用户数据
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      // ==================主要表格

      // 主要弹窗 =============================
      mainForm: {},
      rules: {
        residentialName: [
          { required: true, message: '归属小区不能为空', trigger: 'blur' }
        ],
        spaceCode: [
          { required: true, message: '归属车位不能为空', trigger: 'blur' }
        ],
        managementFeesStart: [
          { required: true, message: '管理费期限不能为空', trigger: 'blur' }
        ],
        count: [
          { required: true, message: '缴费月数不能为空', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '备注不能为空', trigger: 'blur' }
        ],

      },
      mainPopType: '',
      mainPopShow: false,
      // ==============================主要弹窗



      // 选择弹窗=======================
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          if (node.level == 0) {
            let { level } = node;
            this.$api.car.myGetcityList("000000").then(res => {
              res.data.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res.data);
            });
          } else {

            let { level } = node;
            this.$api.car.myGetcityList(node.value).then(res => {
              res.data.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res.data);
            });
          }

        }
      },
      selectPopKeyArea: [],
      selectPopKeyResidentialName: '',
      selectPopKeycarSpaceNumber: '',
      selectShow: false,
      selectType: '',
      selectData: [{ unitName: '5', id: 5 }, { unitName: '1', id: 1 }],



    };
  },
  async activated() {
    this.reset() // 重置清空 然后查询列表
  },
  methods: {

    // 主要按钮 ===============================================================

    addClick() {
      // 清空内容
      {
        this.$set(this.mainForm, 'id', 0)
        this.$set(this.mainForm, 'residentialId', '')
        this.$set(this.mainForm, 'residentialName', '')
        this.$set(this.mainForm, 'spaceId', '')
        this.$set(this.mainForm, 'carSpaceName', '')
        this.$set(this.mainForm, 'ownerName', '')
        this.$set(this.mainForm, 'tenantUserName', '')
        this.$set(this.mainForm, 'amount', '')
        this.$set(this.mainForm, 'count', '')
        this.$set(this.mainForm, 'managementFeesStart', '')
        this.$set(this.mainForm, 'managementFeesEnd', '')
        this.$set(this.mainForm, 'remarks', '')

        this.$nextTick(() => {
          this.$refs.mainForm.clearValidate()
        })
      }

      this.mainPopType = 'add'
      this.mainPopShow = true
    },
    async updateClick(row) {
      let res = await this.$api.car.myParkingSpaceCostDetail(row.id)
      console.log(res.data)
      if (res.code == 200) {
        this.$set(this.mainForm, 'id', res.data.id)
        this.$set(this.mainForm, 'residentialId', res.data.residentialId)
        this.$set(this.mainForm, 'residentialName', res.data.residentialName)
        this.$set(this.mainForm, 'spaceId', res.data.spaceId)
        this.$set(this.mainForm, 'carSpaceName', res.data.code)
        this.$set(this.mainForm, 'ownerName', res.data.belongUserName)
        this.$set(this.mainForm, 'tenantUserName', res.data.tenantUserName)
        this.$set(this.mainForm, 'amount', res.data.amount)
        this.$set(this.mainForm, 'count', res.data.count)
        this.$set(this.mainForm, 'managementFeesStart', res.data.managementFeesStart)
        this.$set(this.mainForm, 'managementFeesEnd', res.data.managementFeesEnd)
        this.$set(this.mainForm, 'remarks', res.data.remarks)

      } else {
        this.$message.error(res.message)
      }
      this.mainPopType = 'update'
      this.mainPopShow = true
    },
    //======================================================================主要按钮

    // 主要弹窗 =============================
    toSelect(val) { //val 小区 车位  乙方
      this.selectType = val

      switch (val) {
        case '小区':

          break;

        case '车位':
          if (!this.mainForm.residentialId) {
            this.$message.error('请您先选择小区')
            return
          }
          break;
      }
      this.getSelectPopData()
      this.selectShow = true
    },
    cascaderChange() {
      this.$nextTick(() => {
        this.getSelectPopData()
        const dom = document.getElementsByClassName("el-radio is-checked")[0];
        if (dom == undefined) return
        const brother = dom.nextElementSibling;
        brother.click();

      });
    },
    getSelectPopData() { //获取选择列表
      //获取表格数据 selectData
      if (this.selectType == '小区') {
        this.getCommunityData()//获取社区列表
      }
      else if (this.selectType == '车位') {
        this.getCarSpaceData()
      }
    },
    async getCommunityData() { //获取社区列表
      let params = {
        "provinceCode": this.selectPopKeyArea[0], //省代号
        "cityCode": this.selectPopKeyArea[1], //市代号
        "districtCode": this.selectPopKeyArea[2], //区代号
        "streetCode": this.selectPopKeyArea[3], //街道代号
        "residentialName": this.selectPopKeyResidentialName //小区名
      }
      let res = await this.$api.car.myGetResidentialList(params)
      if (res.code == 200) {
        this.selectData = res.data
      } else {
        this.$message.error(res.message)
      }
      this.selectData.forEach((el, i) => {
        if (el.residentialId == this.mainForm.residentialId) {
          this.$nextTick(() => {
            this.$refs.selectTable.setCurrentRow(this.selectData[i])
          })
        }
      })
    },
    async getCarSpaceData() { //获取车位列表
      let params = {
        "residentialId": this.mainForm.residentialId, //小区id 必填
        "code": this.selectPopKeycarSpaceNumber, //车位号
      }
      // 车位列表
      let res = await this.$api.car.myParkingSpaceCostSpaceListByResidentialId(params)
      if (res.code == 200) {
        this.selectData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    updataManagementFeesEnd(){
      let dateTime=new Date(this.mainForm.managementFeesStart);
      dateTime.setMonth(dateTime.getMonth() +parseInt(this.mainForm.count));
      this.mainForm.managementFeesEnd = dateTime.toLocaleDateString().replace(/\//g, '-')
    },
    mainPopOk() {
      this.$refs['mainForm'].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let { residentialId, spaceId, amount, managementFeesStart, managementFeesEnd, count, remarks, id } = this.mainForm
            if (this.mainPopType == 'add') {
              let params = { residentialId, spaceId, amount, managementFeesStart, managementFeesEnd, count, remarks }
              let res = await this.$api.car.myParkingSpaceCostInsert(params)
              console.log(res, '新增');
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                });
                this.getTableList()
                this.mainPopShow = false
              } else {
                this.$message.error(res.message)
              }
            } else { //如果是修改
              let params = { residentialId, spaceId, amount, managementFeesStart, managementFeesEnd, count, remarks, id }
              let res = await this.$api.car.myParkingSpaceCostUpdate(params)
              console.log(res, '修改');
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.getTableList()
                this.mainPopShow = false
              } else {
                this.$message.error(res.message)
              }
            }


          }).catch(() => {

          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // ===================================主要弹窗



    selectOk() { // 选择车主确认按钮
      let data = this.$refs['selectTable'].store.states.currentRow
      if (!data) {
        this.$message.error('请先选择数据');
        return
      }
      if (this.selectType == '小区') {
        this.$set(this.mainForm, 'residentialId', data.residentialId)
        this.$set(this.mainForm, 'residentialName', data.name)
      }
      else if (this.selectType == '车位') {
        this.$set(this.mainForm, 'spaceId', data.spaceId)
        this.$set(this.mainForm, 'carSpaceName', data.code)
        this.$set(this.mainForm, 'ownerName', data.belongUserName)
        if (data.tenantUserName) {
          this.$set(this.mainForm, 'tenantUserName', data.tenantUserName)
        }
        if (data.managementFeesEnd) {
          this.$set(this.mainForm, 'managementFeesStart', data.managementFeesEnd)
        }
      }
      // 获取当前表格选中项 this.$refs['selectTable'].store.states.currentRow

      // if (this.$refs['selectTable'].store.states.currentRow) {
      //    ???? = this.$refs['selectTable'].store.states.currentRow
      // }
      this.selectShow = false
    },
    // =================================================================选择弹窗

    // 列表 =====================================================================
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getTableList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.pageNum = 1
      this.key1 = ''
      this.key2 = ''
      this.keyTime = ['', '']
      this.getTableList()
    },
    //按条件查询菜单列表
    async getTableList() {
      if (!this.keyTime) { this.keyTime = ['', ''] }
      let res = await this.$api.car.myParkingSpaceCostList({
        "residentialName": this.key1, //小区名
        "code": this.key2, //车位号
        "start": this.keyTime[0], //开始时间  格式："2024-07-09"
        "end": this.keyTime[1], //结束时间
        "pageSize": this.pageSize,
        "pageNum": this.pageNum
      })
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.TableData = res.data.list;
        this.totalSize = res.data.total;
      } else {
        this.$message.error(res.message)
      }

    },
    // ======================================================================列表

  },


};
</script>
<style scoped lang="less">
.htmbBox {
  display: flex;

  >div {
    &:nth-child(1) {
      width: 30%;
    }

    &:nth-child(2) {
      flex: 1;

      .htmbBox_list {
        width: 100%;

        .el {
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin-bottom: 15px;
        }
      }
    }
  }
}

.tableBox {
  margin-top: 100px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #fafafa;
      }
    }
  }
}

.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {

      // border-left: 1px solid #aaa;
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}



.Top {
  position: relative;

}
</style>
